local nkLibTables = LibStub("nkLibTables");

nkPartyQuest.Core = {};
nkPartyQuest.Core.QuestList = {};

-- Handles party member changes
--
nkPartyQuest.Core.HandlePartyMemberChange = function ()
	
	if (nkPartyQuest.Core.CheckMemberLeft() == true) then
		-- One party member has left (or player has left the party)
		--DEFAULT_CHAT_FRAME:AddMessage("Member left")
		nkPartyQuest.UI.UpdateUI();
	else
		-- New party member
		--DEFAULT_CHAT_FRAME:AddMessage("New party member");
		nkPartyQuest.UI.SetPlayerNames();
		nkPartyQuest.Quests.Snapshot = nkPartyQuest.Core.QuestList[UnitName("player")];
		
		if nkPartyQuest.Core.QuestList[UnitName("player")] ~= nil then
			nkPartyQuest.Com.UpdateTransData(nkPartyQuest.Core.QuestList[UnitName("player")]);
		end;
	end;
end;

-- Checks if a member has left the party
-- Input:	None
-- Output:	true / false
nkPartyQuest.Core.CheckMemberLeft = function ()

	local playerlist = {};
	local retVal = false;
			
	if(UnitExists("party1")) then
		-- Build player list if in party	
		for idx = 1, GetNumPartyMembers()-1 do
			if (UnitExists("party"..idx)) then
				table.insert (playerlist, UnitName("party"..idx));
			end;
		end;
	else
		--DEFAULT_CHAT_FRAME:AddMessage("No party");	
		retVal = true;
	end;

	for k in pairs(nkPartyQuest.Core.QuestList) do
		if k ~= UnitName("player") then
			if nkLibTables.IsMember(playerlist, k) == false then
				-- found a member who left, delete quest information of that player
				nkPartyQuest.Core.QuestList[k] = nil;
				retVal = true;
			end;
		end;
	end;
	
	return retVal;
end;
